package com.dbManage.interceptor;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 访问拦截
 *
 * @author WangDong
 * @date 2018/1/18 18:12
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String pathUrl = request.getServletPath();
        // 1.静态资源跳过
        if (pathUrl.endsWith(".ftl") || pathUrl.startsWith("/js/") || pathUrl.startsWith("/imgs/") ||
                pathUrl.startsWith("/css/") || pathUrl.startsWith("/fonts/") || pathUrl.startsWith("/layui/")) {
            return true;
        }
        // 2.以下请求跳过
        if (pathUrl.startsWith("/login")|| pathUrl.endsWith("/search") || pathUrl.endsWith("/searchView") ||
                pathUrl.endsWith("/searchNewNote")||pathUrl.endsWith("/searchHotNote")||
                pathUrl.startsWith("/test") || pathUrl.startsWith("/getCheckCode") ||
                pathUrl.startsWith("/register") || pathUrl.startsWith("/registerView") ||
                pathUrl.startsWith("/passReset")||pathUrl.startsWith("/changePassword") ||
                pathUrl.startsWith("/record")||pathUrl.startsWith("/test")) {
//            System.out.println("忽略：" + request.getServletPath());
            return true;
        }
        // 3.已登录用户跳过
        if (request.getSession().getAttribute("user") != null) {
//            System.out.println("忽略(已登录)：" + request.getServletPath());
            return true;
        }
        // 4.跳转到登陆页面
        RequestDispatcher rd = request.getRequestDispatcher("/login");
        rd.forward(request, response);
//        response.sendRedirect(request.getContextPath()+"/login");
        return false;
//        return true;
    }
}
